package com.diaohaiwen.common.obj;

import com.diaohaiwen.common.enums.StatusCodeEnum;
import lombok.Data;

import static com.diaohaiwen.common.enums.StatusCodeEnum.SUCCESS;

/**
 * @author 刁海文
 * @since 2023/6/11 16:54
 * @Remark 全局统一结果封装
 */
@Data
public class Result<T> {

    /**
     * 消息提示 数据来源{@link StatusCodeEnum#describe}
     */
    private String msg;

    /**
     * 状态 数据来源{@link StatusCodeEnum#status}
     */
    private int status;

    /**
     * 返回的数据
     */
    private T data;

    public Result() {
    }

    private Result(String msg, int status) {
        this.msg = msg;
        this.status = status;
    }

    private Result(String msg, int status, T data) {
        this.msg = msg;
        this.status = status;
        this.data = data;
    }

    public static Result<?> fail(int status, String msg) {
        return new Result<>(msg, status);
    }

    /**
     * 失败
     *
     * @param code 状态码 {@link StatusCodeEnum}
     * @return Result
     */
    public static Result<?> fail(StatusCodeEnum code) {
        return new Result<>(code.describe, code.status);
    }

    /**
     * 成功
     *
     * @param data 请求数据
     * @param <T>  泛型
     * @return result
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(SUCCESS.describe, SUCCESS.status, data);
    }

    /**
     * 是否执行成功
     *
     * @return true : 成功，false: 失败
     */
    public boolean success() {
        return status == SUCCESS.status;
    }

    /**
     * 是否失败
     *
     * @return true: 失败,false: 成功
     */
    public boolean fail() {
        return !success();
    }

}
